package com.demo.demo.controller

import com.demo.demo.domain.ResultBean
import com.demo.demo.domain.Student
import com.demo.demo.service.StudentService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.*

@RestController
@RequestMapping("students")
class StudentController {
    @Autowired
    private lateinit var studentService: StudentService

    @GetMapping
    fun getStudents() = studentService.getAll()

    @PostMapping
    fun addStudent(
        @RequestParam name: String,
        @RequestParam num: String,
        @RequestParam(required = false) sex: String?
    ): ResultBean {
        val res = try {
            studentService.add(Student(nameString = name, num = num, sex = sex))
        } catch (e: Exception) {
            return ResultBean(1, "数据库操作发生错误", e)
        }
        return if (res) ResultBean(code = 0, message = "添加学生成功，请刷新") else ResultBean(1, message = "添加学生失败")
    }
}